export default {
  data() {
    return {
      formData: {
        name: '',
        phone: ''
      },
      pagination: {
        pageNum: 1,
        pageSize: 20,
        total: 0
      },
      listData: [],
      loading: true,
      tabsActivity: 'agentor',
      QRCodeBase64: '',
    }
  },
  watch: {
    tabsActivity(val) {
      if (this.tabsActivity === 'agentor') {
        this.doSearch()
      } else if (this.tabsActivity === 'rootAgentro') {
        this.getQrCode()
      }
    }
  },
  mounted() {
    this.searchData()
  },
  methods: {
    async searchData() {
      const { pageNum, pageSize } = this.pagination
      const { name, phone } = this.formData

      const params = {
        pageNum,
        pageSize,
        nickName: name,
        phone
      }
      const { success, data, total } = await this.$api.getAgentors(params)
      if (success) {
        this.listData = data.map(d => ({
          ...d,
          totalOrderAmount: d.totalOrderAmount || 0,
          totalOrderIncome: d.totalOrderIncome || 0
        }))
        this.pagination.total = total
      }
      this.loading = false
    },
    doSearch() {
      this.loading = true
      this.pagination.pageNum = 1
      this.searchData()
    },
    handleSizeChange(num) {
      this.pagination.pageSize = num
      this.doSearch()
    },
    handleCurrentChange(num) {
      this.pagination.pageNum = num
      this.loading = true
      this.searchData()
    },
    async getQrCode() {
      this.loading = true
      const response = await this.$api.getRootQrCode()
      const base64Data = `data:image/png;base64,${response.data}`
      this.QRCodeBase64 = base64Data.replace(/[\r\n]/g, '');
      this.loading = false
    },
    downloadQrCode() {
      const a = document.createElement('a')
      a.href = this.QRCodeBase64
      a.setAttribute('download', 'chart-download')
      a.click()
    }
  }
}
